<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';

const router = useRouter();
const filePath = ref('');
const selectedFile = ref(null); // 存储选中的文件对象
const showWarning = ref(true); // 默认显示提示信息
const uploadStatus = ref(''); // 上传状态信息
const showImportCard = ref(false); // 控制导入卡片的显示

// 新增：控制上传功能显示的变量
const showUploadFeature = ref(true);

// 设置相关的响应式变量
const showSettings = ref(false); // 控制设置面板的显示
const customHost = ref('localhost'); // 自定义主机地址
const customPort = ref('8001'); // 自定义端口
const selectedLines = ref({
  'HVAC': true,
}); // 选择要打开的界面

// 新增：加载后端配置
const loadBackendConfig = async () => {
  try {
    const response = await fetch('./config.json');
    const config = await response.json();
    showUploadFeature.value = config.showUploadFeature; // 默认为true
    
    // 如果配置文件中有host和port，也可以作为默认值
    if (config.host) customHost.value = config.host;
    if (config.port) customPort.value = config.port;
  } catch (error) {
    console.log('加载后端配置失败，使用默认设置');
    showUploadFeature.value = true; // 默认显示
  }
};

// 从localStorage加载设置
const loadSettings = () => {
  try {
    const settings = localStorage.getItem('wabtec_settings');
    if (settings) {
      const parsed = JSON.parse(settings);
      customHost.value = parsed.host || 'localhost';
      customPort.value = parsed.port || '8001';
      selectedLines.value = parsed.selectedLines || {
        'HVAC': true,
      };
    }
  } catch (error) {
    console.log('从localStorage读取设置失败，使用默认设置');
  }
};

// 保存设置到localStorage
const saveSettingsToStorage = () => {
  const settings = {
    host: customHost.value,
    port: customPort.value,
    selectedLines: selectedLines.value,
    lastUpdated: new Date().toISOString()
  };
  
  try {
    localStorage.setItem('wabtec_settings', JSON.stringify(settings));
    return true;
  } catch (error) {
    console.error('保存设置失败:', error);
    return false;
  }
};

// 组件挂载时加载设置
onMounted(async () => {
  await loadBackendConfig(); // 先加载后端配置
  loadSettings(); // 再加载用户设置
});

// 切换设置面板显示
const toggleSettings = () => {
  showSettings.value = !showSettings.value;
};

// 保存设置
const saveSettings = () => {
  const success = saveSettingsToStorage();
  if (success) {
    showSettings.value = false;
    uploadStatus.value = '设置已保存';
  } else {
    uploadStatus.value = '设置保存失败';
  }
  setTimeout(() => {
    uploadStatus.value = '';
  }, 2000);
};

// 显示导入卡片
const toggleImportCard = () => {
  showImportCard.value = !showImportCard.value;
};

// 处理文件选择
const handleFileSelect = (event) => {
  const file = event.target.files[0];
  if (file) {
    selectedFile.value = file; // 保存文件对象
    filePath.value = file.name; // 显示文件名
  }
};

// 上传Excel文件
const uploadExcel = async () => {
  if (!selectedFile.value) {
    uploadStatus.value = '请先选择Excel文件';
    return;
  }
  
  uploadStatus.value = '正在上传...';
  
  try {
    // 创建FormData对象
    const formData = new FormData();
    formData.append('file', selectedFile.value);
    
    const response = await fetch(`http://${customHost.value}:${customPort.value}/v1/updateWeekPlanExcel`, {
      method: 'POST',
      body: formData // 直接发送FormData，不需要设置Content-Type，浏览器会自动设置
    });
    
    if (!response.ok) {
      throw new Error(`上传失败: ${response.status}`);
    }
    
    const data = await response.json();
    uploadStatus.value = '上传成功，请启动程序';
    // 上传成功后隐藏导入卡片
    showImportCard.value = false;
  } catch (error) {
    console.error('上传Excel文件失败:', error);
    // 检查是否是TypeError类型且包含Failed to fetch
    if (error instanceof TypeError && error.message.includes('Failed to fetch')) {
      uploadStatus.value = '后端服务未启动，请先启动后端服务';
    } else {
      uploadStatus.value = `上传失败: ${error.message}`;
    }
  }
};

// 启动程序
const launchProgram = async () => {
  // 先进行预检，确认后端有计划数据
  try {
    uploadStatus.value = '正在检查计划数据...';
    
    const response = await fetch(`http://${customHost.value}:${customPort.value}/v1/precheck`, {
      method: 'POST'
    });
    
    if (!response.ok) {
      throw new Error(`检查失败: ${response.status}`);
    }
    
    const data = await response.json();
    
    // hasPlan字段表示是否有计划
    if (!data.hasPlan) {
      uploadStatus.value = '无计划数据，请先上传Excel文件';
      alert(data.message);
      return;
    }
    
    uploadStatus.value = '检查通过，正在启动...';
    
    // 预检通过，继续启动程序
    // 根据用户选择的界面生成urls数组
    const urlMap = {
      'HVAC': window.location.origin + '/#/lines/HVAC',
    };
    
    const urls = Object.keys(selectedLines.value)
      .filter(key => selectedLines.value[key])
      .map(key => urlMap[key]);
    
    if (urls.length === 0) {
      uploadStatus.value = '请至少选择一个界面';
      alert('请至少选择一个界面');
      return;
    }
    
    // 依次打开选中的产线窗口
    urls.forEach((url, index) => {
      setTimeout(() => {
        window.open(url, `productionLines${index+1}`, 'width=1920,height=1080,menubar=no,toolbar=no,location=no,directories=no,status=no,scrollbars=yes,resizable=yes,fullscreen=yes');
      }, 1000 * index);
    });
    
    // 延迟关闭启动界面
    setTimeout(() => {
      window.close(); // 关闭当前窗口（启动界面）
    }, urls.length * 1000 + 500);
    
  } catch (error) {
    console.error('检查计划数据失败:', error);
    // 检查是否是TypeError类型且包含Failed to fetch
    if (error instanceof TypeError && error.message.includes('Failed to fetch')) {
      uploadStatus.value = '后端服务未启动，请先启动后端服务';
      alert('后端服务未启动，请先启动后端服务');
    } else {
      uploadStatus.value = `检查失败: ${error.message}`;
      alert(`检查计划数据失败: ${error.message}`);
    }
  }
};
</script>

<template>
  <div class="launcher-container">
    <div class="header">
      <img src="../assets/wabtec-logo.png" alt="Wabtec Logo" class="logo">
      <!-- 设置图标 -->
      <button @click="toggleSettings" class="settings-button" title="设置">
        ⚙️
      </button>
    </div>
    
    <div class="content-wrapper">
      <h1 class="title">Wabtec生产线监控系统</h1>
      
      <!-- 主要按钮区域 -->
      <div class="main-buttons" v-if="!showImportCard && !showSettings">
        <!-- 只有当 showUploadFeature 为 true 时才显示上传按钮 -->
        <button v-if="showUploadFeature" @click="toggleImportCard" class="import-button">
          <span class="import-icon">📥</span>
          导入新工作计划
        </button>
        
        <button @click="launchProgram" class="launch-button">
          <span class="launch-icon">🚀</span>
          直接启动程序
        </button>
      </div>
      
      <!-- 设置面板 -->
      <div class="card" v-if="showSettings">
        <div class="card-header">
          <h2 class="card-title">系统设置</h2>
          <button @click="toggleSettings" class="close-button">×</button>
        </div>
        
        <div class="compact-section">
          <!-- 后端地址设置 -->
          <div class="setting-group">
            <h3 class="setting-title">后端服务地址</h3>
            <div class="setting-row">
              <label class="setting-label">主机地址:</label>
              <input v-model="customHost" type="text" class="setting-input" placeholder="localhost">
            </div>
            <div class="setting-row">
              <label class="setting-label">端口:</label>
              <input v-model="customPort" type="text" class="setting-input" placeholder="8001">
            </div>
          </div>
          
          <!-- 界面选择设置 -->
          <div class="setting-group">
            <h3 class="setting-title">选择要打开的界面</h3>
            <div class="checkbox-group">
              <label class="checkbox-item">
                <input type="checkbox" v-model="selectedLines['HVAC']">
                <span class="checkbox-label">HVAC</span>
              </label>
            </div>
          </div>
          
          <div class="card-actions">
            <button @click="toggleSettings" class="cancel-button">
              取消
            </button>
            <button @click="saveSettings" class="save-button">
              保存设置
            </button>
          </div>
        </div>
      </div>
      
      <!-- 导入卡片，条件渲染 -->
      <div class="card" v-if="showImportCard">
        <div class="card-header">
          <h2 class="card-title">导入新工作计划或覆盖本周工作计划</h2>
          <button @click="toggleImportCard" class="close-button">×</button>
        </div>
        
        <div class="compact-section">
          <div class="warning-container">
            <div class="warning-message">
              <div class="warning-icon">⚠️</div>
              <p>如以U盘形式导入，则请等启动程序并显示生产线状态界面后再拔出</p>
            </div>
            
            <div class="warning-message">
              <div class="warning-icon">⚠️</div>
              <p>上传新计划Excel，会清除之前的计划Excel以及系统存储的当周实际产量</p>
            </div>
          </div>
          
          <div class="file-row">
            <label for="excel-file" class="file-button">
              <span class="file-icon">📄</span>
              导入新工作计划
            </label>
            <div class="file-path">{{ filePath || '未选择文件' }}</div>
            <button @click="uploadExcel" class="upload-button" :disabled="!filePath">
              上传
            </button>
            <input type="file" id="excel-file" accept=".xlsx,.xls" @change="handleFileSelect" class="file-input">
          </div>
          
          <div class="card-actions">
            <button @click="toggleImportCard" class="cancel-button">
              取消
            </button>
          </div>
        </div>
      </div>
      
      <div class="upload-status-container" v-if="uploadStatus">
        <div class="upload-status">
          {{ uploadStatus }}
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.launcher-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f0f4f8 0%, #d9e2ec 100%);
  padding: 0;
  position: relative;
  font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px 20px;
  background-color: white;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 10;
  box-sizing: border-box;
}

.logo {
  height: 50px;
}

/* 设置按钮样式 */
.settings-button {
  background: none;
  border: none;
  font-size: 1.5rem;
  color: #9ca3af;
  cursor: pointer;
  padding: 8px;
  border-radius: 6px;
  transition: color 0.2s, background-color 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
}

.settings-button:hover {
  color: #6b7280;
  background-color: #f3f4f6;
}

.settings-button:active {
  color: #4b5563;
  background-color: #e5e7eb;
}

.content-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  max-width: 800px;
  width: 100%;
  margin: 0 auto;
  padding: 120px 20px 40px 20px;
  min-height: 100vh;
}

.title {
  font-size: 2.5rem;
  font-weight: 700;
  color: #0056b3;
  margin: 0 0 2.5rem 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  letter-spacing: 1px;
  text-align: center;
}

/* 主按钮区域样式 */
.main-buttons {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
  width: 100%;
  max-width: 400px;
}

.import-button {
  background-color: #0056b3;
  color: white;
  padding: 1rem 1.8rem;
  border: none;
  border-radius: 8px;
  font-size: 1.1rem;
  font-weight: 600;
  cursor: pointer;
  transition: background-color 0.3s, transform 0.2s, box-shadow 0.3s;
  box-shadow: 0 4px 12px rgba(0, 86, 179, 0.3);
  letter-spacing: 1px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.import-icon {
  margin-right: 0.6rem;
  font-size: 1.2rem;
}

.import-button:hover {
  background-color: #004494;
  box-shadow: 0 6px 16px rgba(0, 86, 179, 0.4);
  transform: translateY(-3px);
}

.import-button:active {
  transform: translateY(0);
  box-shadow: 0 4px 12px rgba(0, 86, 179, 0.3);
}

.card {
  width: 100%;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
  padding: 0;
  margin-bottom: 2.5rem;
  transition: transform 0.3s, box-shadow 0.3s;
  overflow: hidden;
  animation: slideDown 0.3s ease-out;
}

@keyframes slideDown {
  from { opacity: 0; transform: translateY(-20px); }
  to { opacity: 1; transform: translateY(0); }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem 1.5rem;
  background-color: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
}

.card-title {
  font-size: 1.3rem;
  color: #0056b3;
  margin: 0;
  font-weight: 600;
}

.close-button {
  background: none;
  border: none;
  font-size: 1.5rem;
  color: #6c757d;
  cursor: pointer;
  padding: 0;
  line-height: 1;
  transition: color 0.2s;
}

.close-button:hover {
  color: #343a40;
}

.compact-section {
  width: 100%;
  padding: 1.5rem;
}

/* 设置相关样式 */
.setting-group {
  margin-bottom: 1.5rem;
}

.setting-title {
  font-size: 1.1rem;
  color: #0056b3;
  margin: 0 0 0.8rem 0;
  font-weight: 600;
}

.setting-row {
  display: flex;
  align-items: center;
  margin-bottom: 0.8rem;
  gap: 1rem;
}

.setting-label {
  min-width: 80px;
  font-size: 0.9rem;
  color: #495057;
  font-weight: 500;
}

.setting-input {
  flex: 1;
  padding: 0.6rem 0.8rem;
  border: 1px solid #ced4da;
  border-radius: 6px;
  font-size: 0.9rem;
  transition: border-color 0.2s, box-shadow 0.2s;
}

.setting-input:focus {
  outline: none;
  border-color: #0056b3;
  box-shadow: 0 0 0 2px rgba(0, 86, 179, 0.1);
}

.checkbox-group {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 0.8rem;
}

.checkbox-item {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 0.5rem;
  border-radius: 6px;
  transition: background-color 0.2s;
}

.checkbox-item:hover {
  background-color: #f8f9fa;
}

.checkbox-item input[type="checkbox"] {
  margin-right: 0.5rem;
  transform: scale(1.1);
}

.checkbox-label {
  font-size: 0.9rem;
  color: #495057;
  user-select: none;
}

.warning-container {
  margin-bottom: 1rem;
  background-color: #fff9e6;
  border-radius: 8px;
  padding: 0.5rem;
}

.warning-message {
  display: flex;
  align-items: flex-start;
  margin-bottom: 0.5rem;
  padding: 0.5rem 0.8rem;
  border-radius: 6px;
  border-left: 4px solid #ffc107;
  font-size: 0.9rem;
  background-color: rgba(255, 255, 255, 0.7);
}

.warning-message:last-child {
  margin-bottom: 0;
}

.warning-icon {
  font-size: 1.1rem;
  margin-right: 0.8rem;
  line-height: 1;
}

.warning-message p {
  margin: 0;
  color: #664d03;
  font-size: 0.9rem;
  line-height: 1.5;
}

.file-row {
  display: flex;
  align-items: center;
  margin: 1rem 0 0.5rem;
  gap: 0.8rem;
}

.file-input {
  display: none;
}

.file-button {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  background-color: #0056b3;
  color: white;
  padding: 0.6rem 1rem;
  border-radius: 6px;
  cursor: pointer;
  font-size: 0.9rem;
  font-weight: 500;
  white-space: nowrap;
  min-width: 160px;
  text-align: center;
  transition: background-color 0.3s, transform 0.2s;
  box-shadow: 0 2px 6px rgba(0, 86, 179, 0.3);
}

.file-icon {
  margin-right: 0.5rem;
  font-size: 1.1rem;
}

.file-button:hover {
  background-color: #004494;
  transform: translateY(-2px);
}

.file-button:active {
  transform: translateY(0);
}

.file-path {
  flex: 1;
  padding: 0.6rem 1rem;
  background-color: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
  font-family: monospace;
  font-size: 0.9rem;
  color: #495057;
  height: 40px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.05);
}

.upload-button {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  background-color: #6c757d;
  color: white;
  padding: 0.6rem 1rem;
  border: none;
  border-radius: 6px;
  font-size: 0.9rem;
  font-weight: 500;
  cursor: pointer;
  min-width: 80px;
  white-space: nowrap;
  transition: background-color 0.3s, transform 0.2s;
  box-shadow: 0 2px 6px rgba(108, 117, 125, 0.3);
}

.upload-button:hover:not(:disabled) {
  background-color: #5a6268;
  transform: translateY(-2px);
}

.upload-button:active:not(:disabled) {
  transform: translateY(0);
}

.upload-button:disabled {
  background-color: #adb5bd;
  cursor: not-allowed;
  box-shadow: none;
}

.card-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 1.5rem;
}

.cancel-button {
  background-color: #f8f9fa;
  color: #495057;
  border: 1px solid #ced4da;
  padding: 0.5rem 1rem;
  border-radius: 6px;
  font-size: 0.9rem;
  cursor: pointer;
  transition: background-color 0.2s;
}

.cancel-button:hover {
  background-color: #e9ecef;
}

.save-button {
  background-color: #0056b3;
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 6px;
  font-size: 0.9rem;
  cursor: pointer;
  transition: background-color 0.2s;
}

.save-button:hover {
  background-color: #004494;
}

.upload-status-container {
  width: 100%;
  max-width: 800px;
  margin-top: 1.5rem;
}

.upload-status {
  font-size: 0.95rem;
  color: #495057;
  padding: 0.8rem 1rem;
  background-color: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #0056b3;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  animation: fadeIn 0.3s ease-in-out;
}

.launch-button {
  background-color: #28a745;
  color: white;
  padding: 1rem 1.8rem;
  border: none;
  border-radius: 8px;
  font-size: 1.1rem;
  font-weight: 600;
  cursor: pointer;
  transition: background-color 0.3s, transform 0.2s, box-shadow 0.3s;
  box-shadow: 0 4px 12px rgba(40, 167, 69, 0.3);
  letter-spacing: 1px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.launch-icon {
  margin-right: 0.6rem;
  font-size: 1.2rem;
}

.launch-button:hover {
  background-color: #218838;
  box-shadow: 0 6px 16px rgba(40, 167, 69, 0.4);
  transform: translateY(-3px);
}

.launch-button:active {
  transform: translateY(0);
  box-shadow: 0 4px 12px rgba(40, 167, 69, 0.3);
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

@media (max-width: 768px) {
  .title {
    font-size: 2rem;
  }
  
  .file-row {
    flex-direction: column;
    align-items: stretch;
  }
  
  .file-button, .upload-button {
    margin-bottom: 0.8rem;
  }
  
  .file-path {
    margin-bottom: 0.8rem;
  }
  
  .card {
    padding: 0;
  }
  
  .compact-section {
    padding: 1.2rem;
  }
  
  .main-buttons {
    max-width: 100%;
  }
  
  .checkbox-group {
    grid-template-columns: 1fr;
  }
}
</style>
